#include "Common.hpp"

void Usage(const std::string &name)
{
    std::cout << "usage: " << name << " + ip" << " + port" << std::endl;
}

int main(int argc, char *args[])
{
    if (argc != 3)
    {
        Usage(args[0]);
        exit(USAGE_ERROR);
    }

    in_port_t port = std::stoi(args[2]);
    InetAddr server(args[1], port);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        LOG(LogLevel::FATAL) << "socket: 套接字创建失败! " << std::strerror(errno);
        exit(SOCKET_ERROR);
    }

    int n = connect(sockfd, server.NetAddrPtr(), server.AddrLen());
    if (n == -1)
    {
        LOG(LogLevel::FATAL) << "connect: 建立连接失败! " << std::strerror(errno);
        exit(CONNECT_ERROR);
    }

    std::string message;
    char buffer[BUFFER_SIZE];
    while (true)
    {
        std::cout << "Send to server# ";
        std::getline(std::cin, message);
        ssize_t n = write(sockfd, message.c_str(), message.size());
        if (n == -1)
        {
            LOG(LogLevel::ERROR) << "write: [" << server.Info() << "]写入数据时出错! " << std::strerror(errno);
            exit(WRITE_ERROR);
        }
        n = read(sockfd, buffer, sizeof(buffer) - 1);
        if(n == -1)
        {
            LOG(LogLevel::ERROR) << "read: [" << server.Info() << "]读取数据时出错! " << std::strerror(errno);
            exit(READ_ERROR);
        }
        buffer[n] = 0;
        std::cout << "Recive from server: " << buffer << std::endl;
    }
    return 0;
}